'use strict';

const {
	Controller
} = require('uni-cloud-router');

module.exports = class MpController extends Controller {

	// 首页
	async home() {
		let {
			rows,
			shop_id
		} = this.ctx.data;
		console.log(this.ctx.data)
		rows = rows || 8;
		let response = {
			carousel: [],
			category: [],
			limited: [],
			hot: []
		};
		if(!shop_id){
			response.code = 1;
			response.msg = '店铺ID为空';
			return response
		}
		let start = Date.now();
		const carousel = this.db.collection('wmzmall-app-carousel').where({
			shop_id:shop_id,
			state: '启用'
		}).orderBy('sort', 'asc').field({
			name: true,
			img: true,
			type: true,
			url: true,
			remark: true
		}).get();
		const category = this.db.collection('wmzmall-app-category').where({
			shop_id:shop_id,
			state: '启用'
		}).orderBy('sort', 'asc').field({
			name: true,
			img: true,
			type: true,
			url: true,
			remark: true
		}).get();
		const limited = this.db.collection('wmzmall-goods').where({
			shop_id:shop_id,
			state: '销售中',
			limited: 1
		}).orderBy('limited_sort', 'asc').limit(rows).field({
			sort: false,
			limited: false,
			hot: false,
			search_tags: false,
			visit_cnt: false,
			collect_cnt: false,
			share_cnt: false,
			sold_out_time: false,
			state: false,
			imgs: false,
			skus: false,
			share_title: false,
			share_img: false,
			share_desc: false,
			last_modify_uname: false,
			last_modify_uid: false
		}).get();
		const hot = this.db.collection('wmzmall-goods').where({
			shop_id:shop_id,
			state: '销售中',
			hot: 1
		}).orderBy('hot_sort', 'asc').limit(rows).field({
			sort: false,
			limited: false,
			hot: false,
			search_tags: false,
			visit_cnt: false,
			collect_cnt: false,
			share_cnt: false,
			sold_out_time: false,
			state: false,
			imgs: false,
			skus: false,
			share_title: false,
			share_img: false,
			share_desc: false,
			last_modify_uname: false,
			last_modify_uid: false
		}).get();
		const parameter = this.db.collection('wmzmall-app-parameter').limit(1).get();
		
		const datas = await Promise.all([carousel, category, limited, hot, parameter]);
		
		response.carousel = datas[0] && datas[0].data;
		response.category = datas[1] && datas[1].data;
		response.limited = datas[2] && datas[2].data;
		response.hot = datas[3] && datas[3].data;
		response.parameter = datas[4] && datas[4].data[0];
		response.code = 0;
		let end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

}
